#!/bin/sh

me=`basename "$0"`
for pid in $(pidof -x $me); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : Process $me is already running with PID $pid"
        exit 1
    fi
done

#cd ~/dev-domoticz

# To be able to upload, you need one time to login to the upload server
# ssh -l USERNAME upload.domoticz.com

UPLOAD_USER="USERNAME"
UPLOAD_PASSWORD="PASSWORD"

lowercase(){
    echo "$1" | sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/"
}

OS=`lowercase \`uname -s\``
# KERNEL=`uname -r`
MACH=`uname -m`

archive_file="domoticz_${OS}_${MACH}.tgz"
version_file="version_${OS}_${MACH}.h"
history_file="history_${OS}_${MACH}.txt"

# Make sure we are on latest commit
echo "Updating to server revision..."
git fetch --all

TOTCOUNT="$(git rev-list HEAD...origin/master --count)"
if [ "$TOTCOUNT" -lt 1 ]; then
        echo "No Changes..."
        exit;
fi

git reset --hard origin/master

cmake -DCMAKE_BUILD_TYPE=Release .
if [ $? -ne 0 ]
then
	echo "CMake failed!";
	exit 1
fi
make -j 2
if [ $? -ne 0 ]
then
	echo "Compilation failed!...";
	exit 1
fi
echo "Success, making release...";

cp -f appversion.h ${version_file}
cp -f History.txt ${history_file}

# Generate the archive
echo "Generating Archive: ${archive_file}..."

if [ -f ${archive_file} ];
then
  rm ${archive_file}
fi
if [ -f ${archive_file}.sha256sum ];
then
  rm ${archive_file}.sha256sum
fi

tar -zcf ${archive_file} domoticz History.txt License.txt domoticz.sh server_cert.pem updatebeta updaterelease www/ scripts/ Config/ plugins/ dzVents/
if [ $? -ne 0 ]
then
        echo "Error creating archive!...";
        exit 1
fi
echo "Creating checksum file...";
hash="$(sha256sum ${archive_file} | sed -e 's/\s.*$//')  update.tgz";
echo $hash > ${archive_file}.sha256sum
if [ ! -f ${archive_file}.sha256sum ];
then
        echo "Error creating archive checksum file!...";
        exit 1
fi

#################################
echo "Uploading to Cloud...";
sshpass -p ${UPLOAD_PASSWORD} scp -o User=${UPLOAD_USER} ${archive_file} ${archive_file}.sha256sum ${version_file} ${history_file} 146.185.159.228:/home/uploads@domoticz.com/release
if [ $? -ne 0 ]
then
        echo "Error uploading to Cloud!...";
        exit 1
fi
#################################

# Cleaning up
rm -f ${version_file}
rm -f ${history_file}

echo "Done!...";
cat appversion.h
exit 0;
